package com.nativetalk.service.three.ranking;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.FoundChange.TdNtMembFoundChangeInset;
import com.nativetalk.bean.FoundChange.TdNtTeaFoundChangeInsert;
import com.nativetalk.bean.WeekRankingVirtualUser;
import com.nativetalk.bean.member.TdNtMemberClcokIn;
import com.nativetalk.bean.ranking.TdNtWeekRankingList;
import com.nativetalk.bean.ranking.TdNtWeekRankingListInsert;
import com.nativetalk.bean.ranking.TdNtWeekRankingListTeacher;
import com.nativetalk.bean.teacher.TdNtTeacherGetui;
import com.nativetalk.bean.teacher.TdNtTeacherIndex;
import com.nativetalk.bean.website.TsNtWebSiteConfIndex;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.MemcachedKey;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.dao.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by lizhun on 16/8/25.
 */
@Service
public class RankingServiceImpl implements RankingService {
    private static Logger logger = Logger.getLogger(RankingServiceImpl.class);
    @Resource
    private TdNtWeekRankingListDao tdNtWeekRankingListDao;
    @Resource
    private TdNtStudyTeachDao tdNtStudyTeachDao;
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TdNtMembFoundChangeDao tdNtMembFoundChangeDao;
    @Resource
    private TdNtTeacherDao tdNtTeacherDao;
    @Resource
    private TdNtTeaFoundChangeDao tdNtTeaFoundChangeDao;

    @Resource
    private WeekRankingVirtualUserDao weekRankingVirtualUserDao;

    @Override
    public RetInfo findWeekRanking(int memb_id) {
        String logInfo = this.getClass().getName() + ":findWeekRanking:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {

            List<TdNtWeekRankingListInsert> tdNtWeekRankingListInserts = tdNtWeekRankingListDao.searchTdNtTeacherListPage(1);

            List<WeekRankingVirtualUser> virturalStudents = weekRankingVirtualUserDao.findVirtualStudent();
            Map<Integer, WeekRankingVirtualUser> virturalStudentsMap = initMap(virturalStudents);

            List<TdNtWeekRankingList> tdNtWeekRankingLists = new ArrayList<>();
            int week_study_size = 0;
            Timestamp timestamp = tdNtWeekRankingListInserts.get(0).getTimestamp();
            for (TdNtWeekRankingListInsert studentWeekRank : tdNtWeekRankingListInserts) {
                TdNtWeekRankingList tdNtWeekRankingList = new TdNtWeekRankingList();

                //虚拟用户
                if (studentWeekRank.getMemb_id() == null || studentWeekRank.getMemb_id().intValue() == 0) {
                    WeekRankingVirtualUser student = virturalStudentsMap.get(studentWeekRank.getVirtual_user_id());
                    tdNtWeekRankingList.setMemb_head_portrait(student.getAvatar());
                    tdNtWeekRankingList.setMemb_name(CommonUtil.starMiddleName(student.getName()));
                    tdNtWeekRankingList.setRanking(studentWeekRank.getRanking());
                    tdNtWeekRankingList.setRanking_size(studentWeekRank.getRanking_size());
                } else {
                    // 真实用户
                    tdNtWeekRankingList.setMemb_head_portrait(studentWeekRank.getMemb_head_portrait());
                    tdNtWeekRankingList.setMemb_name(studentWeekRank.getMemb_name());
                    tdNtWeekRankingList.setRanking(studentWeekRank.getRanking());
                    tdNtWeekRankingList.setRanking_size(studentWeekRank.getRanking_size());

                    // 将用户的名字中间部分用***号替换，自己的名字不替换
                    if (studentWeekRank.getMemb_id().intValue() == memb_id) {
                        tdNtWeekRankingList.setIs_ranking(0);
                        week_study_size = studentWeekRank.getRanking_size();
                    } else {
                        String name = CommonUtil.starMiddleName(studentWeekRank.getMemb_name());
                        tdNtWeekRankingList.setMemb_name(name);
                    }
                }

                tdNtWeekRankingLists.add(tdNtWeekRankingList);
            }
            if (week_study_size == 0) {
                TdNtWeekRankingListInsert tdNtWeekRankingListInsert = new TdNtWeekRankingListInsert();
                tdNtWeekRankingListInsert.setMemb_id(memb_id);
                tdNtWeekRankingListInsert.setTimestamp(timestamp);
                tdNtWeekRankingListInsert.setWeek_type(1);
                TdNtWeekRankingListInsert result = tdNtWeekRankingListDao.findTdNtWeekRankingListByMembId(tdNtWeekRankingListInsert);
                if (result != null) {
                    week_study_size = result.getRanking_size();
                } else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("start_time", CommonUtil.getLastWeekStartTime(true));
                    map.put("end_time", CommonUtil.getLastWeekStartTime(false));
                    map.put("memb_id", memb_id);
                    week_study_size = tdNtStudyTeachDao.findMemberStudyWeekSize(map);
                    tdNtWeekRankingListInsert.setRanking(999);
                    tdNtWeekRankingListInsert.setRanking_size(week_study_size);
                    tdNtWeekRankingListInsert.setReceive_reward(1);
                    tdNtWeekRankingListInsert.setReward(new BigDecimal(0));
                    tdNtWeekRankingListInsert.setWeek_type(1);
                    tdNtWeekRankingListDao.intsertWeekRakingList(tdNtWeekRankingListInsert);
                }
            }
            Map<String, Object> result = new HashMap<>();
            result.put("weekRankingList", tdNtWeekRankingLists);
            result.put("week_study_size", week_study_size);
            Map<String, TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String, TsNtWebSiteConfIndex>) MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);
            result.put("share", tsNtWebSiteConfIndexMap.get("27").getData_value());
            result.put("share_name", tsNtWebSiteConfIndexMap.get("28").getData_value());
            result.put("share_url", Constants.member_ranking_url + memb_id);
            result.put("share_picutre", Constants.DOMAIN + "nativetalk/WechatIMG2.png");
            result.put("share_content", tsNtWebSiteConfIndexMap.get("28").getData_value());
            retInfo.setObj(result);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取排行榜成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    private Map<Integer, WeekRankingVirtualUser> initMap(List<WeekRankingVirtualUser> virturalStudents) {
        Map<Integer, WeekRankingVirtualUser> map = new HashMap<>();
        for (WeekRankingVirtualUser user : virturalStudents) {
            map.put(user.getId(), user);
        }
        return map;
    }

    @Override
    public RetInfo findReviceWeekRanking(int memb_id) {
        String logInfo = this.getClass().getName() + ":findReviceWeekRanking:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {

            /**
             * 查找用户是否可领取奖励
             */
            Map<String, Integer> params = new HashMap<>();
            params.put("week_type", TdNtWeekRankingListInsert.BonusType.student);//week_type  1：学生排行榜；2：老师排行榜
            params.put("memb_id", memb_id);
            TdNtWeekRankingListInsert tdNtWeekRankingListInsert = tdNtWeekRankingListDao.findTdNtWeekRankingByMembId(params);

            Map<String, Object> map = new HashMap<>();
            int rankSize = tdNtWeekRankingListInsert.getRanking_size();
            map.put("week_study_size", rankSize);
            map.put("total_reward", tdNtMemberDao.findMemberTotalReward(memb_id));
            /**
             * 领奖规则：1.前3名，2.上周累计学习时间大于0分钟（前3名奖励金额：20、10、5）
             */
            if (tdNtWeekRankingListInsert.getRanking() <= 3 && rankSize > 0) {
                /**
                 * 判断奖励是否已领取
                 */
                if (tdNtWeekRankingListInsert.getReceive_reward() == TdNtWeekRankingListInsert.Receive_reward_status.yes) {
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("您已领取奖励" + tdNtWeekRankingListInsert.getReward() + "学币");
                    map.put("bonus_status", TdNtWeekRankingListInsert.Receive_reward_status.yes);// 已领奖
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip("您可领取奖励" + tdNtWeekRankingListInsert.getReward() + "学币");
                    map.put("bonus_status", TdNtWeekRankingListInsert.Receive_reward_status.no);// 未领奖
                }
            } else {
                map.put("bonus_status", TdNtWeekRankingListInsert.Receive_reward_status.losing);// 未上榜单，不够领奖资格
                int thridStudySize = tdNtWeekRankingListDao.findThreeStudySize(TdNtWeekRankingListInsert.BonusType.student);//上周第3名的学习时长（分钟）
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("很遗憾，上周您距离奖金只差" + (thridStudySize - rankSize) + "分钟，本周加油哦！");
            }
            retInfo.setObj(map);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    @Transactional
    public RetInfo reviceWeekRanking(int memb_id) {
        String logInfo = this.getClass().getName() + ":reviceWeekRanking:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {

            /**
             * 查找用户是否可领取奖励
             */
            Map<String, Integer> params = new HashMap<>();
            params.put("week_type", 1);
            params.put("memb_id", memb_id);
            TdNtWeekRankingListInsert tdNtWeekRankingListInsert = tdNtWeekRankingListDao.findTdNtWeekRankingByMembId(params);
            /**
             * 判断用户是否是前三名
             */
            if (tdNtWeekRankingListInsert.getRanking() <= 3) {
                /**
                 * 判断奖励是否已领取
                 */
                if (tdNtWeekRankingListInsert.getReceive_reward() == 0) {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip("已领取");

                } else {

                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("领取成功");
                    tdNtWeekRankingListInsert.setReceive_reward(0);
                    tdNtWeekRankingListDao.update(tdNtWeekRankingListInsert);
                    //更新用户余额
                    BigDecimal memb_balance = tdNtMemberDao.findTdNtMemberBalabce(memb_id);
                    if (memb_balance == null) {
                        memb_balance = new BigDecimal(0);
                    }
                    BigDecimal reward = tdNtWeekRankingListInsert.getReward();
                    if (reward == null) {
                        reward = new BigDecimal(0);
                    }

                    //添加一条资金变动记录
                    TdNtMembFoundChangeInset tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();
                    tdNtMembFoundChangeInset.setMemb_id(memb_id);
                    tdNtMembFoundChangeInset.setMfchg_change_amount(reward);
                    tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                    tdNtMembFoundChangeInset.setMfchg_change_name("周排行奖励");
//                    tdNtMembFoundChangeInset.setMfchg_change_name("其它");
                    tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_in);
                    tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                    tdNtMembFoundChangeInset.setType(Constants.ChargeType.other_code);
                    tdNtMembFoundChangeInset.setMfchg_number(CommonUtil.getOrderNub());
                    tdNtMembFoundChangeInset.setMfchg_back_amount(memb_balance.add(reward));
                    tdNtMembFoundChangeInset.setMfchg_front_amount(memb_balance);
                    tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                    Map<String, Object> updateReward = new HashMap<>();
                    updateReward.put("memb_id", memb_id);
                    updateReward.put("memb_balance", memb_balance.add(reward));

                    BigDecimal totalReward = tdNtMemberDao.findMemberTotalReward(memb_id);

                    if (totalReward == null) {
                        totalReward = new BigDecimal(0);
                    }

                    updateReward.put("total_reward", reward.add(totalReward));
                    tdNtMemberDao.updateMemberTotalReward(updateReward);
                }
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("不可领取奖励");
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo findTeacherWeekRanking(int tea_id) {
        String logInfo = this.getClass().getName() + ":findTeacherWeekRanking:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {

            List<TdNtWeekRankingListInsert> tdNtWeekRankingListInserts = tdNtWeekRankingListDao.searchWeekRakingListPage(2);

            List<WeekRankingVirtualUser> virturalTeachers = weekRankingVirtualUserDao.findVirtualTeacher();
            Map<Integer, WeekRankingVirtualUser> virturalStudentsMap = initMap(virturalTeachers);

            List<TdNtWeekRankingListTeacher> tdNtWeekRankingLists = new ArrayList<>();
            int week_teach_size = 0;
            if (tdNtWeekRankingListInserts != null && tdNtWeekRankingListInserts.size() > 0) {
                Timestamp timestamp = tdNtWeekRankingListInserts.get(0).getTimestamp();
                //将 Entity转换为DTO
                for (TdNtWeekRankingListInsert teacherWeekRank : tdNtWeekRankingListInserts) {
                    TdNtWeekRankingListTeacher tdNtWeekRankingList = new TdNtWeekRankingListTeacher();
                    //虚拟用户
                    if (teacherWeekRank.getMemb_id() == null || teacherWeekRank.getMemb_id().intValue() == 0) {
                        WeekRankingVirtualUser teacher = virturalStudentsMap.get(teacherWeekRank.getVirtual_user_id());
                        tdNtWeekRankingList.setTea_head_portrait(teacher.getAvatar());
                        tdNtWeekRankingList.setTea_name(CommonUtil.starMiddleName(teacher.getName()));
                        tdNtWeekRankingList.setRanking(teacherWeekRank.getRanking());
                        tdNtWeekRankingList.setRanking_size(teacherWeekRank.getRanking_size());
                    } else {
                        // 真实用户
                        tdNtWeekRankingList.setTea_head_portrait(teacherWeekRank.getTea_head_portrait());
                        tdNtWeekRankingList.setTea_name(teacherWeekRank.getTea_name());
                        tdNtWeekRankingList.setRanking(teacherWeekRank.getRanking());
                        tdNtWeekRankingList.setRanking_size(teacherWeekRank.getRanking_size());

                        if (teacherWeekRank.getMemb_id() == tea_id) {
                            tdNtWeekRankingList.setIs_ranking(0);
                            week_teach_size = teacherWeekRank.getRanking_size();
                        } else {
                            String name = CommonUtil.starMiddleName(tdNtWeekRankingList.getTea_name());
                            tdNtWeekRankingList.setTea_name(name);
                        }
                    }
                    tdNtWeekRankingLists.add(tdNtWeekRankingList);
                }

                if (week_teach_size == 0) {
                    TdNtWeekRankingListInsert tdNtWeekRankingListInsert = new TdNtWeekRankingListInsert();
                    tdNtWeekRankingListInsert.setMemb_id(tea_id);
                    tdNtWeekRankingListInsert.setTimestamp(timestamp);
                    tdNtWeekRankingListInsert.setWeek_type(2);
                    TdNtWeekRankingListInsert result = tdNtWeekRankingListDao.findTdNtWeekRankingListByMembId(tdNtWeekRankingListInsert);
                    if (result != null) {
                        week_teach_size = result.getRanking_size();
                    } else {
                        Map<String, Object> map = new HashMap<>();
                        map.put("start_time", CommonUtil.getLastWeekStartTime(true));
                        map.put("end_time", CommonUtil.getLastWeekStartTime(false));
                        map.put("tea_id", tea_id);
                        week_teach_size = tdNtStudyTeachDao.findTeacherTeachWeekSize(map);
                        tdNtWeekRankingListInsert.setRanking(999);
                        tdNtWeekRankingListInsert.setRanking_size(week_teach_size);
                        tdNtWeekRankingListInsert.setReceive_reward(1);
                        tdNtWeekRankingListInsert.setReward(new BigDecimal(0));
                        tdNtWeekRankingListInsert.setWeek_type(2);
                        tdNtWeekRankingListDao.intsertWeekRakingList(tdNtWeekRankingListInsert);
                    }
                }
            }
            Map<String, Object> result = new HashMap<>();
            result.put("weekRankingList", tdNtWeekRankingLists);
            result.put("week_teach_size", week_teach_size);
            Map<String, TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String, TsNtWebSiteConfIndex>) MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);
            result.put("share", tsNtWebSiteConfIndexMap.get("27").getData_value());
            result.put("share_name", tsNtWebSiteConfIndexMap.get("28").getData_value());
            result.put("share_url", Constants.teacher_ranking_url + tea_id);
            result.put("share_picutre", Constants.DOMAIN + "nativetalk/WechatIMG2.png");
            result.put("share_content", tsNtWebSiteConfIndexMap.get("28").getData_value());
            retInfo.setObj(result);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取排行榜成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo findTeacherReviceWeekRanking(int tea_id) {
        String logInfo = this.getClass().getName() + ":findTeacherReviceWeekRanking:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            /**
             * 查找用户是否可领取奖励
             */
            Map<String, Integer> params = new HashMap<>();
            params.put("week_type", TdNtWeekRankingListInsert.BonusType.teacher);
            params.put("memb_id", tea_id);
            TdNtWeekRankingListInsert tdNtWeekRankingListInsert = tdNtWeekRankingListDao.findTdNtWeekRankingByMembId(params);

            int rankSize = tdNtWeekRankingListInsert.getRanking_size();//上周教学时长
            Map<String, Object> map = new HashMap<>();
            map.put("week_teach_size", rankSize);
            map.put("total_reward", tdNtTeacherDao.findTeacherTotalReward(tea_id));

            /**
             * 判断用户是否是前三名
             */
            if (tdNtWeekRankingListInsert.getRanking() <= 3) {
                /**
                 * 判断奖励是否已领取
                 */
                if (tdNtWeekRankingListInsert.getReceive_reward() == TdNtWeekRankingListInsert.Receive_reward_status.yes) {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(tdNtWeekRankingListInsert.getReward() + " dollars bonus earned!\n");
                    map.put("bonus_status", TdNtWeekRankingListInsert.Receive_reward_status.yes);// 已领奖

                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("You can get " + tdNtWeekRankingListInsert.getReward() + " dollars bonus!");
                    map.put("bonus_status", TdNtWeekRankingListInsert.Receive_reward_status.no);// 未领奖
                }
            } else {
                int thridStudySize = tdNtWeekRankingListDao.findThreeStudySize(TdNtWeekRankingListInsert.BonusType.teacher);//上周第3名的学习时长（分钟）
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip((thridStudySize - rankSize) + " minutes left to get the new bonus");
                map.put("bonus_status", TdNtWeekRankingListInsert.Receive_reward_status.losing);// 未上榜单，不够领奖资格
            }
            retInfo.setObj(map);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    @Transactional
    public RetInfo reviceTeacherWeekRanking(int tea_id) {
        String logInfo = this.getClass().getName() + ":reviceWeekRanking:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {

            /**
             * 查找用户是否可领取奖励
             */
            Map<String, Integer> params = new HashMap<>();
            params.put("week_type", TdNtWeekRankingListInsert.BonusType.teacher);
            params.put("memb_id", tea_id);
            TdNtWeekRankingListInsert tdNtWeekRankingListInsert = tdNtWeekRankingListDao.findTdNtWeekRankingByMembId(params);
            /**
             * 判断用户是否是前三名
             */
            if (tdNtWeekRankingListInsert.getRanking() <= 3) {
                /**
                 * 判断奖励是否已领取
                 */
                if (tdNtWeekRankingListInsert.getReceive_reward() == TdNtWeekRankingListInsert.Receive_reward_status.yes) {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip("已领取");

                } else {

                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("领取成功");
                    tdNtWeekRankingListInsert.setReceive_reward(TdNtWeekRankingListInsert.Receive_reward_status.yes);
                    tdNtWeekRankingListDao.update(tdNtWeekRankingListInsert);
                    /**
                     * 添加教师资金变动记录
                     */
                    TdNtTeacherIndex tdNtTeacherIndex = tdNtTeacherDao.findTdNtTeacherIndex(tea_id);
                    BigDecimal teacherBalance = tdNtTeacherIndex.getTea_balance();
                    if (teacherBalance == null) {
                        teacherBalance = new BigDecimal(0);
                    }
                    BigDecimal reward = tdNtWeekRankingListInsert.getReward();
                    if (reward == null) {
                        reward = new BigDecimal(0);
                    }
                    TdNtTeaFoundChangeInsert tdNtTeaFoundChangeInsert = new TdNtTeaFoundChangeInsert();
                    tdNtTeaFoundChangeInsert.setState("2");
                    tdNtTeaFoundChangeInsert.setTea_id(tea_id);
                    tdNtTeaFoundChangeInsert.setTfchg_account(new BigDecimal("0"));
                    tdNtTeaFoundChangeInsert.setTfchg_front_amount(teacherBalance);
                    tdNtTeaFoundChangeInsert.setTfchg_change_amount(reward);
                    tdNtTeaFoundChangeInsert.setTfchg_back_amount(teacherBalance.add(reward));
                    tdNtTeaFoundChangeInsert.setTfchg_change_month(CommonUtil.getMonth(now));
                    tdNtTeaFoundChangeInsert.setTfchg_change_type("1");
                    tdNtTeaFoundChangeInsert.setTfchg_counter_fee(new BigDecimal("0"));
                    tdNtTeaFoundChangeInsert.setTfchg_number(CommonUtil.getOrderNub());
                    tdNtTeaFoundChangeInsert.setTfchg_change_name("Reward");
                    tdNtTeaFoundChangeInsert.setType(3);
                    tdNtTeaFoundChangeDao.insertTdNtTeaFoundChangeInsert(tdNtTeaFoundChangeInsert);

                    Map<String, Object> updateReward = new HashMap<>();
                    updateReward.put("tea_id", tea_id);
                    updateReward.put("tea_balance", teacherBalance.add(reward));
                    BigDecimal totalReward = tdNtTeacherDao.findTeacherTotalReward(tea_id);
                    if (totalReward == null) {
                        totalReward = new BigDecimal(0);
                    }
                    updateReward.put("tea_total_reward", reward.add(totalReward));
                    tdNtTeacherDao.updateTeacherTotalReward(updateReward);
                }
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("不可领取奖励");
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo findWeekRankingShare(int memb_id) {
        String logInfo = this.getClass().getName() + ":findWeekRankingShare:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {

            List<TdNtWeekRankingListInsert> tdNtWeekRankingListInserts = tdNtWeekRankingListDao.searchTdNtTeacherListPage(1);

            List<WeekRankingVirtualUser> virturalStudents = weekRankingVirtualUserDao.findVirtualStudent();
            Map<Integer, WeekRankingVirtualUser> virturalStudentsMap = initMap(virturalStudents);

            List<TdNtWeekRankingList> tdNtWeekRankingLists = new ArrayList<>();
            int week_study_size = 0;
            Timestamp timestamp = tdNtWeekRankingListInserts.get(0).getTimestamp();
            for (TdNtWeekRankingListInsert studentWeekRank : tdNtWeekRankingListInserts) {
                TdNtWeekRankingList tdNtWeekRankingList = new TdNtWeekRankingList();

                //虚拟用户
                if (studentWeekRank.getMemb_id() == null) {
                    WeekRankingVirtualUser student = virturalStudentsMap.get(studentWeekRank.getVirtual_user_id());
                    tdNtWeekRankingList.setMemb_head_portrait(student.getAvatar());
                    tdNtWeekRankingList.setMemb_name(CommonUtil.starMiddleName(student.getName()));
                    tdNtWeekRankingList.setRanking(studentWeekRank.getRanking());
                    tdNtWeekRankingList.setRanking_size(studentWeekRank.getRanking_size());
                } else {
                    // 真实用户
                    tdNtWeekRankingList.setMemb_head_portrait(studentWeekRank.getMemb_head_portrait());
                    tdNtWeekRankingList.setMemb_name(studentWeekRank.getMemb_name());
                    tdNtWeekRankingList.setRanking(studentWeekRank.getRanking());
                    tdNtWeekRankingList.setRanking_size(studentWeekRank.getRanking_size());

                    // 将用户的名字中间部分用***号替换，自己的名字不替换
                    if (studentWeekRank.getMemb_id().intValue() == memb_id) {
                        tdNtWeekRankingList.setIs_ranking(0);
                        week_study_size = studentWeekRank.getRanking_size();
                    } else {
                        String name = CommonUtil.starMiddleName(studentWeekRank.getMemb_name());
                        tdNtWeekRankingList.setMemb_name(name);
                    }
                }

                tdNtWeekRankingLists.add(tdNtWeekRankingList);
            }
            if (week_study_size == 0) {
                TdNtWeekRankingListInsert tdNtWeekRankingListInsert = new TdNtWeekRankingListInsert();
                tdNtWeekRankingListInsert.setMemb_id(memb_id);
                tdNtWeekRankingListInsert.setTimestamp(timestamp);
                tdNtWeekRankingListInsert.setWeek_type(1);
                TdNtWeekRankingListInsert result = tdNtWeekRankingListDao.findTdNtWeekRankingListByMembId(tdNtWeekRankingListInsert);
                if (result != null) {
                    week_study_size = result.getRanking_size();
                } else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("start_time", CommonUtil.getLastWeekStartTime(true));
                    map.put("end_time", CommonUtil.getLastWeekStartTime(false));
                    map.put("memb_id", memb_id);
                    week_study_size = tdNtStudyTeachDao.findMemberStudyWeekSize(map);
                    tdNtWeekRankingListInsert.setRanking(999);
                    tdNtWeekRankingListInsert.setRanking_size(week_study_size);
                    tdNtWeekRankingListInsert.setReceive_reward(1);
                    tdNtWeekRankingListInsert.setReward(new BigDecimal(0));
                    tdNtWeekRankingListInsert.setWeek_type(1);
                    tdNtWeekRankingListDao.intsertWeekRakingList(tdNtWeekRankingListInsert);
                }
            }
            TdNtMemberClcokIn tdNtMemberClcokIn = tdNtMemberDao.findMemberClockInDay(memb_id);
            Map<String, Object> result = new HashMap<>();
            result.put("weekRankingList", tdNtWeekRankingLists);
            result.put("week_study_size", week_study_size);
            result.put("memb_head_portrait", tdNtMemberClcokIn.getMemb_head_portrait());
            result.put("memb_name", tdNtMemberClcokIn.getMemb_name());
            retInfo.setObj(result);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取排行榜成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo findTeacherWeekRankingShare(int tea_id) {
        String logInfo = this.getClass().getName() + ":findTeacherWeekRankingShare:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {

            List<TdNtWeekRankingListInsert> tdNtWeekRankingListInserts = tdNtWeekRankingListDao.searchWeekRakingListPage(2);

            List<WeekRankingVirtualUser> virturalTeachers = weekRankingVirtualUserDao.findVirtualTeacher();
            Map<Integer, WeekRankingVirtualUser> virturalStudentsMap = initMap(virturalTeachers);

            List<TdNtWeekRankingListTeacher> tdNtWeekRankingLists = new ArrayList<>();
            int week_teach_size = 0;
            Timestamp timestamp = tdNtWeekRankingListInserts.get(0).getTimestamp();
            //将 Entity转换为DTO
            for (TdNtWeekRankingListInsert teacherWeekRank : tdNtWeekRankingListInserts) {
                TdNtWeekRankingListTeacher tdNtWeekRankingList = new TdNtWeekRankingListTeacher();
                //虚拟用户
                if (teacherWeekRank.getMemb_id() == null) {
                    WeekRankingVirtualUser teacher = virturalStudentsMap.get(teacherWeekRank.getVirtual_user_id());
                    tdNtWeekRankingList.setTea_head_portrait(teacher.getAvatar());
                    tdNtWeekRankingList.setTea_name(CommonUtil.starMiddleName(teacher.getName()));
                    tdNtWeekRankingList.setRanking(teacherWeekRank.getRanking());
                    tdNtWeekRankingList.setRanking_size(teacherWeekRank.getRanking_size());
                } else {
                    // 真实用户
                    tdNtWeekRankingList.setTea_head_portrait(teacherWeekRank.getTea_head_portrait());
                    tdNtWeekRankingList.setTea_name(teacherWeekRank.getTea_name());
                    tdNtWeekRankingList.setRanking(teacherWeekRank.getRanking());
                    tdNtWeekRankingList.setRanking_size(teacherWeekRank.getRanking_size());

                    if (teacherWeekRank.getMemb_id() == tea_id) {
                        tdNtWeekRankingList.setIs_ranking(0);
                        week_teach_size = teacherWeekRank.getRanking_size();
                    } else {
                        String name = CommonUtil.starMiddleName(tdNtWeekRankingList.getTea_name());
                        tdNtWeekRankingList.setTea_name(name);
                    }
                }
                tdNtWeekRankingLists.add(tdNtWeekRankingList);
            }

            if (week_teach_size == 0) {
                TdNtWeekRankingListInsert tdNtWeekRankingListInsert = new TdNtWeekRankingListInsert();
                tdNtWeekRankingListInsert.setMemb_id(tea_id);
                tdNtWeekRankingListInsert.setTimestamp(timestamp);
                tdNtWeekRankingListInsert.setWeek_type(2);
                TdNtWeekRankingListInsert result = tdNtWeekRankingListDao.findTdNtWeekRankingListByMembId(tdNtWeekRankingListInsert);
                if (result != null) {
                    week_teach_size = result.getRanking_size();
                } else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("start_time", CommonUtil.getLastWeekStartTime(true));
                    map.put("end_time", CommonUtil.getLastWeekStartTime(false));
                    map.put("tea_id", tea_id);
                    week_teach_size = tdNtStudyTeachDao.findTeacherTeachWeekSize(map);
                    tdNtWeekRankingListInsert.setRanking(999);
                    tdNtWeekRankingListInsert.setRanking_size(week_teach_size);
                    tdNtWeekRankingListInsert.setReceive_reward(1);
                    tdNtWeekRankingListInsert.setReward(new BigDecimal(0));
                    tdNtWeekRankingListInsert.setWeek_type(2);
                    tdNtWeekRankingListDao.intsertWeekRakingList(tdNtWeekRankingListInsert);
                }
            }
            Map<String, Object> result = new HashMap<>();
            result.put("weekRankingList", tdNtWeekRankingLists);
            result.put("week_teach_size", week_teach_size);
            TdNtTeacherGetui tdNtTeacherGetui = tdNtTeacherDao.findTdNtTeacher(tea_id);
            result.put("tea_head_portrait", tdNtTeacherGetui.getTea_head_portrait());
            result.put("tea_name", tdNtTeacherGetui.getTea_name());
            retInfo.setObj(result);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取排行榜成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
